from ..database import database, TABLE_PREFIX
from   peewee import *
import datetime
from playhouse.signals import pre_save
from .member import Member

from playhouse.signals import post_save


class AuthHistory(database.Model):
    id = PrimaryKeyField(db_column='id')
    member = ForeignKeyField(Member)
    created_at = DateTimeField(db_column='created_at', help_text='创建时间', default=datetime.datetime.now)
    login_ip = CharField(db_column='login_ip', max_length=20, help_text='登陆IP', null=True)
    country = CharField(db_column='country', max_length=40, help_text='国家', null=True)
    city = CharField(db_column='city', help_text='登陆城市', max_length=60)
    platform = CharField(db_column='platform', help_text='登陆平台', default='web', max_length=20)
    platform_identify = CharField(db_column='platform_identify', max_length=600, null=True)
    status = CharField(db_column='status', max_length=10, default='normal')
    access_token = CharField(db_column='access_token', max_length=60, help_text='授权码')
    #
    # class Meta:
    #     db_table = "{}_auth_histories".format(TABLE_PREFIX)


class LocalAuth(database.Model):
    id = PrimaryKeyField(db_column='id')
    login_name = CharField(db_column='login_name', max_length=120, help_text='登陆名称')
    password = CharField(db_column='password', max_length=120, help_text='密码')
    retry_count = IntegerField(db_column='retry_count', default=0, help_text='密码重试次数')
    created_at = DateTimeField(db_column='created_at', help_text='创建时间', default=datetime.datetime.now)
    updated_at = DateTimeField(db_column='updated_at', help_text='更新时间', default=datetime.datetime.now)
    last_retry_time  = DateTimeField(db_column='last_retry_time',help_text='最后重试时间',null=True)
    # last_login_at = DateTimeField(db_column='last_login_at', help_text='最后登陆时间', null=True)
    # last_login_ip = CharField(db_column='last_login_ip', help_text='最后登陆ip', null=True)
    member = ForeignKeyField(Member)

    # class Meta:
    #     db_table = '{}_local_auths'.format(TABLE_PREFIX)

    @classmethod
    def exist(cls, login_name):
        return LocalAuth.get_or_none(LocalAuth.login_name == login_name) is not None

    def verify_password(self,password):
        return self.password  == _encrypt_password(password)


@LocalAuth.pre_save.connect
def pre_save_handler(instance, created):
    if created:
        instance.password = _encrypt_password(instance.password)

#
# @pre_save(sender=LocalAuth)
# def pre_save_handler(model, instance, created):
#     if created:
#         instance.password = _encrypt_password(instance.password)

def _encrypt_password(password):
    import hashlib
    sha1 = hashlib.sha1()
    sha1.update(password.encode())
    return sha1.hexdigest()
